package com.example.nio.network.subreactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 *  selector.wakeup(); 在不同的jdk，不同的os下都有bug；目前win11有很多bug，试了一天不得行
 */
public class Acceptor implements Runnable{

    // 只需要一个ServerSocketChannel就行了
    private final ServerSocketChannel serverChannel;

    public Acceptor(ServerSocketChannel serverChannel) throws IOException {
        this.serverChannel = serverChannel;
    }

    @Override
    public void run() {
        try{
            // 还是正常进行Accept操作，得到SocketChannel
            SocketChannel channel = serverChannel.accept();
            System.out.println("客户端已连接，IP地址为："+channel.getRemoteAddress());
            channel.configureBlocking(false);

            // 选取下一个从Reactor的Selector
            Selector selector = SubReactor.nextSelector();
            // 在注册之前唤醒一下防止卡死
            selector.wakeup();
            // 注意现在注册的是从Reactor的Selector
            channel.register(selector, SelectionKey.OP_READ, new Handler(channel));
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}